/**
 * 
 */
package com.cqndt.disaster.device.common.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.Args;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

/**
 * @author Administrator
 *
 */
public class HttpUtil {
	
	public class ParamValuePair {
		
	}
	/** 
	 * 普通数据post上传
	 * 
	 * @param url
	 *            请求的url地址
	 *
	 * @return 服务器响应值
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String doPost(String url, Map<String, String> params) throws ClientProtocolException, IOException {

		
		return null;
	}
	
	/** 
	 * 普通数据post上传
	 * 
	 * @param url
	 *            请求的url地址
	 *
	 * @return 服务器响应值
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String doPost(String url, List<String> params,List<String> values) throws ClientProtocolException, IOException {
		
		Args.notNull(params, "参数名不能为空");
		Args.notNull(values, "参数值不能为空");
		Args.check(params.size()==values.size(), "参数名和值数量必须等同");
		
		 CloseableHttpClient httpclient = HttpClients.createDefault();
		 String reslut = null;
	        try {
	            HttpPost httpPost = new HttpPost(url);
	            
	            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	            for (int i=0;i<params.size();i++){
	            	nvps.add(new BasicNameValuePair(params.get(i), values.get(i)));
	            }
	            
	            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
	            CloseableHttpResponse response = httpclient.execute(httpPost);
	          
	            try {
	                
	                int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                       HttpEntity entity = response.getEntity();
                       reslut = EntityUtils.toString(entity);
                       EntityUtils.consume(entity);
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
	            } finally {
	                response.close();
	            }
	        } finally {
	            httpclient.close();
	        }
		return reslut;
	}
	
	
	public static Map<String,Map<String,String>> json2map(String json){
		//Map<String, String> result = new HashMap<>();
		 ObjectMapper mapper = new ObjectMapper(); //转换器
		 Map<String,Map<String,String>> m =  null;
		 try {
			m = mapper.readValue(json,Map.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
		 return m;
	}
	
	/**
	 * change json to object
	 * @param json
	 * @param object
	 * @return
	 * @throws IOException
	 */
	public static <T> T json2Object(String json, Class<T> object) throws  IOException{
		 ObjectMapper mapper = new ObjectMapper(); //转换器
		 T t =  mapper.readValue(json, object);
		 return t;
	}
	
	/**
	 * appKey: '18cd831a5ece4f87bfbe4f6593df2e5e',
	   appSecret: '1dbba1ea53944ae77f7d89e9801588b7',
	   https://open.ys7.com/api/lapp/token/get
	 * @param args
	 * @throws IOException 
	 * @throws ClientProtocolException
	 */
	public static void main(String[] args) throws ClientProtocolException, IOException {
		List<String> params  = new ArrayList<>();
		List<String> values  = new ArrayList<>();
		
		params.add("appKey");
		params.add("appSecret");
		
		values.add("18cd831a5ece4f87bfbe4f6593df2e5e");
		values.add("1dbba1ea53944ae77f7d89e9801588b7");
		
		String reslut= doPost("https://open.ys7.com/api/lapp/token/get", params, values);
		System.out.println(reslut);
		
//		List<String> params  = new ArrayList<>();
//		List<String> values  = new ArrayList<>();
//		String url = "https://open.ys7.com/api/lapp/device/ptz/stop";
//		
//		//String accessToken = "at.97agaoew6h7ufy7e5iay4ejl4a47fgdk-9kdba9gvbd-1iorrlm-tyuar8vh1";
//		String exireTime = SimpleDateFormat.getInstance().format(new Date(1505107469193l));
//		params.add("accessToken");
//		values.add("at.97agaoew6h7ufy7e5iay4ejl4a47fgdk-9kdba9gvbd-1iorrlm-tyuar8vh1");
//		params.add("deviceSerial");
//		values.add("778584659");
//		params.add("channelNo");
//		values.add("1");
//		params.add("direction");
//		values.add("10");
//		params.add("speed");
//		values.add("1");
//		
//		
//		String reslut= doPost(url, params, values);
//		System.out.println(reslut);
		Map<String,Map<String,String>> result = json2Object(reslut, Map.class);
		System.out.println(result.get("data").get("accessToken"));
	}
	
	public static void readJson2Map() {
        String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
                    "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
        try {
        	 ObjectMapper objectMapper = new ObjectMapper(); //转换器
            Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
            System.out.println(maps.size());
            Set<String> key = maps.keySet();
            Iterator<String> iter = key.iterator();
            while (iter.hasNext()) {
                String field = iter.next();
                System.out.println(field + ":" + maps.get(field));
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


